/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.uhk.ppro.traveler.logic;

import cz.uhk.ppro.traveler.dao.UsersDao;
import cz.uhk.ppro.traveler.entity.TUser;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author Martin Soušek
 */
public class LoginActionBean extends BaseActionBean {
    
    @ValidateNestedProperties({
        
        @Validate(field="username",required=true),
        @Validate(field="password",required=true)
    })
    private TUser user;
    
    private TUser currentUser = null;
    
    @SpringBean("users")
    private UsersDao usersDao;
    
    private String errorMsg;
    
    // Actions
    @DefaultHandler
    public Resolution login() {
        
        currentUser = usersDao.getUser(this.user.getUsername());
        
        if (currentUser == null) {
            
            errorMsg = "Wrong username or password.";
            return new ForwardResolution("/WEB-INF/jsp/error.jsp");
        }
        
        else {
            
            if ((currentUser.getPassword().equals(user.getPassword()))) {
                
                getContext().setCurrentUser(currentUser);
//                getContext().getCurrentUser().getBudget().calculateTotal();
                getContext().getCurrentUser().calcRemainingTrips();
                return new ForwardResolution("/WEB-INF/jsp/trips.jsp"); // change back to home.jsp
            }
            
            else {
                
                errorMsg = "Wrong username or password.";
                return new ForwardResolution("/WEB-INF/jsp/error.jsp");
            }
        }
        
    }
    
    // Accessors
    public TUser getUser() {
        return user;
    }

    public void setUser(TUser user) {
        this.user = user;
    }

    public TUser getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(TUser currentUser) {
        this.currentUser = currentUser;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
